package com.cy.db.sys.service.impl;

import com.cy.db.common.exception.ServiceException;
import com.cy.db.common.pojo.PageObject;
import com.cy.db.sys.dao.SysUserDao;
import com.cy.db.sys.dao.SysUserRoleDao;
import com.cy.db.sys.entity.SysUser;
import com.cy.db.sys.service.SysUserService;
import com.cy.db.sys.vo.SysUserDeptVO;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Override
    public PageObject<SysUserDeptVO> findPageObjects(String username, Long pageCurrent) {
        //1.对参数进行校验
        if(pageCurrent == null || pageCurrent < 1){
            throw new IllegalArgumentException("当前页码值无效");
        }
        //2.查询总记录数并进行校验
        long rowCount = sysUserDao.getRowCount(username);
        if(rowCount == 0){
            throw new ServiceException("没有找到对应的记录");
        }
        //3.查询当前页记录
        int pageSize = 3;//页面大小(每页最多显示多少条记录)
        long startIndex = (pageCurrent-1) * pageSize; //起始位置
        List<SysUserDeptVO> records = sysUserDao.findPageObjects(username, startIndex, pageSize);
        //4.对查询结果进行封装并返回
        return new PageObject<>(rowCount,records,pageSize,pageCurrent);
    }

    @Override
    public int validById(Integer id, Integer valid) {
        //1.参数校验
        if(id == null || id <= 0){
            throw new IllegalArgumentException("参数值无效");
        }
        if(valid == null || (valid!=1 && valid!=0) ){
            throw new IllegalArgumentException("状态值无效");
        }
        //2.更改状态
        int row = sysUserDao.validById(id, valid,"admin");
        if(row == 0){
            throw new ServiceException("记录可能已经不存在");
        }
        return row;
    }

    @Override
    public int saveObject(SysUser entity,Integer[] roleIds) {
        //1.校验参数
        if(entity == null){
            throw new IllegalArgumentException("保存的对象不能为空");
        }
        if(entity.getUsername() == null || "".equals(entity.getUsername())){
            throw new IllegalArgumentException("用户名不能为空");
        }
        if(entity.getPassword() == null || "".equals(entity.getPassword())){
            throw new IllegalArgumentException("密码不能为空");
        }
        if(roleIds == null || roleIds.length == 0){
            throw new IllegalArgumentException("至少为用户分配角色");
        }
        //2.保存用户自身信息
        //2.1构建盐值
       String salt = UUID.randomUUID().toString();
        //借助shiro框架中的API对密码进行加密
        SimpleHash sh = new SimpleHash(
                "MD5", //算法的名称
                entity.getPassword(),//未加密的密码
                salt,//加密盐
                1);//加密的次数
        String hashPassword = sh.toHex();//将加密结果转换为16进制的字符串
        entity.setSalt(salt);
        entity.setPassword(hashPassword);
        // 2.2 将用户信息写入到数据库
        int row = sysUserDao.insertObject(entity);
        //3.保存用户与角色关系数据
        sysUserRoleDao.insertObjects(entity.getId(),roleIds);
        return row;
    }

    @Override
    public Map<String, Object> findObjectById(Integer userId) {
        //1.参数校验
        if(userId == null){
            throw new IllegalArgumentException("用户id不能为空");
        }
        //2.业务查询
        SysUserDeptVO user = sysUserDao.findObjectById(userId);
        if(user == null){
            throw new IllegalArgumentException("用户已经不存在");
        }
        List<Integer> roleIds = sysUserRoleDao.findRoleIdsByUserId(userId);
        //3.封装数据
        Map<String,Object> map = new HashMap<>();
        map.put("user",user);
        map.put("roleIds",roleIds);
        return map;
    }

    @Override
    public int updateObject(SysUser entity,Integer[] roleIds) {
        //1.参数校验
        if(entity == null){
            throw new IllegalArgumentException("修改的对象不能为空");
        }
        if(entity.getUsername() == null){
            throw new IllegalArgumentException("用户名不能为空");
        }
        if(roleIds == null || roleIds.length == 0){
            throw new IllegalArgumentException("必须为用户分配角色");
        }
        //2.保存用户自身信息
        int row = sysUserDao.updateObject(entity);
        //3.保存用户与角色关系数据
        sysUserRoleDao.deleteObjectsByUserId(entity.getId());
        sysUserRoleDao.insertObjects(entity.getId(),roleIds);
        return row;
    }
}
